package org.imsoss.pcscf;

import java.util.ArrayList;
import java.util.ListIterator;

import javax.naming.Context;
import javax.naming.InitialContext;

import javax.sip.ClientTransaction;
import javax.sip.ServerTransaction;
import javax.sip.SipProvider;
import javax.sip.address.Address;
import javax.sip.address.AddressFactory;
import javax.sip.address.SipURI;
import javax.sip.header.CSeqHeader;
import javax.sip.header.CallIdHeader;
import javax.sip.header.FromHeader;
import javax.sip.header.HeaderFactory;
import javax.sip.header.MaxForwardsHeader;
import javax.sip.header.ToHeader;
import javax.sip.header.ViaHeader;
import javax.sip.message.MessageFactory;
import javax.sip.message.Request;
import javax.sip.message.Response;

import javax.slee.ActivityContextInterface;
import javax.slee.SbbContext;
import javax.slee.facilities.TimerFacility;
import javax.slee.nullactivity.NullActivityContextInterfaceFactory;
import javax.slee.nullactivity.NullActivityFactory;

import org.apache.log4j.Logger;

import org.mobicents.slee.resource.sip.SipResourceAdaptorSbbInterface;
import org.mobicents.slee.services.sip.common.SipSendErrorResponseException;
import org.mobicents.slee.services.sip.location.LocationSbbLocalObject;
import org.mobicents.slee.services.sip.location.LocationServiceException;
import org.mobicents.slee.services.sip.location.RegistrationBinding;

import org.imsoss.sbb.CommonSbb;
import org.imsoss.util.ImsConfiguration;
import org.imsoss.util.SipMessageDelegator;

public abstract class ProxySbb extends CommonSbb{
	
	public void onServiceStarted(
			javax.slee.serviceactivity.ServiceStartedEvent serviceEvent,
			ActivityContextInterface aci) {
		
		//logger.debug("Starting P-CSCF node of the imsoss ;) sexy ");
		System.out.println("Starting P-CSCF node of the imsoss ;) sexy ");
	}

	/**
	 * Event handler for the SIP MESSAGE(REGISTER) from the UA
	 * @param event
	 * @param aci
	 */
	public void onRegisterEvent(javax.sip.RequestEvent event, ActivityContextInterface aci) {
		
		Request request = event.getRequest();
		
		org.imsoss.refpoint.ReferencePoint gmRefPoint = new org.imsoss.refpoint.gm.GmReferencePoint(provider, addressFactory, headerFactory, messageFactory);		
		gmRefPoint.processOnRegister(request);
		
		
		/*
		try{
		Response response = messageFactory.createResponse(Response.OK,request);
		syslog("response \n"+response);
		Object activity = aci.getActivity();			
		syslog(activity);
		syslog("--->"+sbbContext.getActivities().length);
		syslog("--->"+sbbContext.getActivities()[0]);
		event.getServerTransaction().sendResponse(response);
		}
		catch(Exception e){
			syslog(e);
		}
		*/
		
	}
						
	/**
	 *  Initialize the component
	 */
	public void setSbbContext(SbbContext context) { 

		this.sbbContext = context;
		try {
	            Context myEnv = (Context) new InitialContext().lookup("java:comp/env");
	                        
	            // Getting SLEE Factility
	            timerFacility = (TimerFacility) myEnv.lookup("slee/facilities/timer");
	            nullACIFactory = (NullActivityContextInterfaceFactory)myEnv.
	            				lookup("slee/nullactivity/activitycontextinterfacefactory");
	            nullActivityFactory = (NullActivityFactory)myEnv.lookup("slee/nullactivity/factory");
	            
	            // Getting JAIN SIP Resource Adaptor interfaces            
	            fp = (SipResourceAdaptorSbbInterface) myEnv.lookup("slee/resources/jainsip/1.2/provider");
	            
	            provider = fp.getSipProvider();
	            
	            addressFactory = fp.getAddressFactory();
	            headerFactory = fp.getHeaderFactory();
	            messageFactory = fp.getMessageFactory();
            
        	} catch (Exception ne) {
           		logger.error("Failed to set sbb context",ne);
        	}		
	}

	public void onOkEvent(javax.sip.ResponseEvent event, ActivityContextInterface aci){
		syslog(getClass()+" Entering onOKEvent");
		/*
		try{
			Response response = event.getResponse();
			ListIterator<ViaHeader> iter = response.getHeaders(ViaHeader.NAME);
			// Check if the viaHeader contains i-cscf
			boolean icscfPassed = false;
			
			while(iter.hasNext()){
				ViaHeader viaHeader = iter.next();
				if(viaHeader.getPort() != ImsConfiguration.icscfPort){										
					icscfPassed = true;
				}
			}
			if(icscfPassed){
				syslog("p-cscf should process the OK event and pass this to UE.");
			}
			else{
				// ignore
				syslog("Ignore OK event");
			}
		}
		catch(Exception e){
			syslog("Error in onOkEvent"+e);
		}
		*/
		//syslog("******** p-cscf listens to OK event which is fired from the s-cscf"+"\n"+event.getResponse());
	}
    public abstract org.imsoss.pcscf.ProxySbbActivityContextInterface asSbbActivityContextInterface(ActivityContextInterface aci);
 
	private SbbContext sbbContext; 
	
	private MessageFactory messageFactory;
	private SipProvider provider;
	private SipResourceAdaptorSbbInterface fp;
	private TimerFacility timerFacility;
	private NullActivityContextInterfaceFactory nullACIFactory;
	private NullActivityFactory nullActivityFactory;
	private AddressFactory addressFactory;
	private HeaderFactory headerFactory;
	
	private static final Logger logger = Logger.getLogger(ProxySbb.class); 
	
}



/*
REGISTER sip:proxy.sea.com SIP/2.0  // REGISTER sip:p-cscf:p-cscf-node SIP/2.0
Via: SIP/2.0/UDP 1.2.3.4:5060;branch=z9hG4bKjjf9d45
Max-Forwards: 70
To: <sip:john@sea.com>
From: <sip:john@sea.com>;tag=635529
Call-ID: 99183245223553@43je8ew9236
CSeq: 540 REGISTER
Contact: <sip:john@1.2.3.4>
Expires: 6300
Content-Length: 0
*/